<?php
/*

___Canvas Import Functions______________________________________

Imports function name and variable definitions from an XML file.

________________________________________________________________

*/

function canvas_delete_block($block_id) {
	global $wpdb, $canvas;
	$wpdb->query("DELETE FROM ".$canvas->main." WHERE block_id = '$block_id'");
	if($variables = $wpdb->get_results("SELECT variable_id, type FROM ".$canvas->variables." WHERE parent = '$block_id'")) {
		foreach($variables as $variable) {
			$wpdb->query("DELETE FROM ".$canvas->variables." WHERE parent = '$block_id'");
			if($variable->type == 'Radio' || $variable->type == 'Image' || $variable->type == 'Select')
				$wpdb->query("DELETE FROM ".$canvas->options." WHERE var_id = '".$variable->variable_id."'");
		}
	}
}

function canvas_duplicate_block($block_id) {
	global $wpdb, $canvas;
	if($wpdb->get_var("SELECT zone FROM ".$canvas->main." WHERE block_id = '$block_id'")) {
		$block_info = $wpdb->get_results("SELECT * FROM ".$canvas->main." WHERE block_id = '$block_id'");
		// look for other duplicates
		if($other_blocks = $wpdb->get_results("SELECT block_name, block_id FROM ".$canvas->main." WHERE theme = '".$block_info[0]->theme."' AND block_name LIKE '".preg_replace('/\scopy\s[0-9]*/', '', $block_info[0]->block_name)." %' ORDER BY block_id DESC")) {
			if($other_blocks[0]->block_id != $block_id) {
				$block_info[0]->block_id = $other_blocks[0]->block_id;
				$block_info[0]->block_name = $other_blocks[0]->block_name;
			}
		}
		// go ahead and rename, then duplicate
		$testcase = substr($block_info[0]->block_name, -1, 1);
		if(ctype_digit($testcase))
			$block_info[0]->block_name[strlen($block_info[0]->block_name) - 1] = intval($testcase) + 1;
		else
			$block_info[0]->block_name .= ' copy 2';
		if(!$block_info[0]->position = ($wpdb->get_var("SELECT MAX(position) FROM ".$canvas->main." WHERE zone = 'shelf' AND theme = '".$block_info[0]->theme."'")) + 1) $block_info[0]->position = 1;
		$block_info[0]->zone = 'shelf';
		
		$results=$wpdb->get_results("SELECT * FROM ".$canvas->main." WHERE block_id = $block_id");
		foreach($results as $result) {		
			$query = $wpdb->query("INSERT INTO ".$canvas->main." (block_name, type, zone, position, author, description, block_group, uri, path, theme, ubi) VALUES ('".$block_info[0]->block_name."','".$result->type."','".$block_info[0]->zone."', '".$block_info[0]->position."','".$result->author."','".$result->description."','".$result->block_group."','".$result->uri."','".$result->path."','".$result->theme."','".$result->ubi."')");
		}
		$block_info[0]->block_id = $wpdb->get_var("SELECT block_id FROM ".$canvas->main." WHERE block_name = '".$block_info[0]->block_name."' AND theme = '".$block_info[0]->theme."'");
		// duplicate variables
		if($block_info[0]->type == 'plugin') {
			$results=$wpdb->get_results("SELECT * FROM ".$canvas->variables." WHERE parent = '$block_id' ORDER BY variable_id");
			foreach($results as $result) {
				$wpdb->query("INSERT INTO ".$canvas->variables." (variable_name, parent, type, value, default_value, description) VALUES ('".$result->variable_name."','".$block_info[0]->block_id."','".$result->type."','".$result->value."','".$result->default_value."','".addslashes($result->description)."')");
			}
			// handle variable options
			$old_option_vars = $wpdb->get_results("SELECT variable_id FROM ".$canvas->variables." WHERE parent = '$block_id' AND (type = 'Radio' OR type = 'Image' OR type = 'Select') ORDER BY variable_id");
			$new_option_vars = $wpdb->get_results("SELECT variable_id FROM ".$canvas->variables." WHERE parent = '".$block_info[0]->block_id."' AND (type = 'Radio' OR type = 'Image' OR type = 'Select') ORDER BY variable_id");
			for($i = 0; $i < count($old_option_vars); $i++) :
				$results=$wpdb->get_results("SELECT '".$new_option_vars[$i]->variable_id."', option_text, option_value FROM ".$canvas->options." WHERE var_id = '".$old_option_vars[$i]->variable_id."' ORDER BY var_id");
				foreach($results as $result) {
					$wpdb->query("INSERT INTO ".$canvas->options." (var_id, option_text, option_value) VALUES ('".$new_option_vars[$i]->variable_id."','".$result->option_text."','".$result->option_value."')");		
				}
			endfor;
		}
		return $block_info[0];
	}
}

function canvas_import_blocks($position, $dir='') {
	if($dir=='') return false;
    $blocks = array();
	if (substr($dir,-1) != '/') $dir .= '/';
	$files = scandirectory($dir);
	foreach($files as $filename) {
		if(substr($filename, -3) == 'php') {
			$block_data = canvas_parse_block_data($dir.$filename);
			if (!empty($block_data['Name'])) {
			  $position = canvas_install_block_data($block_data,$position);
			  $blocks[] = $block_data['Name'];
            }
		}
	}
	
	return array($blocks, $position);
}

function canvas_import_form() {
?>
<div class="lbContent">
<h3>Import from XML
<p>If you're using a correctly built Canvas-compatible theme, you can import layout schemes from other users.</p>
<a id="cancel" href="javascript:void(0)" class="lbAction" rel="cancel">Cancel</a>
</h3>
<div>
	<form id="canvas_export">
		<p>Canvas can load layout and Canvas plugin data through a special XML file. To import a layout, be sure to use an XML file for the theme that you are currently working with.</p>
		<p>Importing from XML is still experimental, and may result in loss of Canvas-related data.</p>
		<label class="textbox">Path to the XML file on your server:<input class="text" type="text" id="path_to_xml" name="path_to_xml" value="" /></label>
		<input type="button" id="import_canvas" name="import_canvas" value="Import" onclick="Canvas.importXml()"/>
	</form>
	<p id="export_message"></p>
</div>
</div>

<?php
}

function canvas_import_layout($filename) {
	if(!file_exists($filename)) { echo 'File does not exist.'; return; }
	global $wpdb, $canvas, $imported_theme, $imported_blocks, $imported_variables, $id, $current_tag;
	$imported_theme = array();
	$imported_blocks = array();
	canvas_reload();

	if(!($xmlparser = xml_parser_create()))
		$error = "ERROR: Cannot create parser for ".$filename;
	xml_set_element_handler($xmlparser, "startElement", "endElement");
	xml_set_character_data_handler($xmlparser, "canvas_import_layout_XML");

	if(!($fp = fopen($filename, "r")))
		$error = "ERROR: Cannot open ".$filename;
	while($data = fread($fp, 4096)) {
		$data = eregi_replace(">"."[[:space:]]+"."<","><",$data);
        $data = eregi_replace(">"."[[:space:]]+",">",$data);
        $data = eregi_replace("[[:space:]]+"."<","<",$data);
		
		if (!xml_parse($xmlparser, $data, feof($fp)))
			$error = "XML error parsing ".$filename;
	}
	xml_parser_free($xmlparser);

	$block_ids = $wpdb->get_results("SELECT block_id FROM ".$canvas->main." WHERE theme = '".get_option('template')."'");
	foreach($block_ids as $block_id) {
		canvas_delete_block($block_id->block_id);
	}
	canvas_install(); // clean install

	foreach($imported_blocks as $key => $block) {
		$old_block = $wpdb->get_results("SELECT block_id, zone FROM ".$canvas->main." WHERE ubi = '".$block['ubi']."'");
		$old_block = $old_block[0];
		if($old_block->zone != 'shelf') $old_block = canvas_duplicate_block($old_block->block_id);
		
		$wpdb->query("UPDATE ".$canvas->main." SET zone = '".$block['zone']."', position = '".$block['position']."' WHERE block_id = '".$old_block->block_id."'");
		if($imported_variables && $block['type'] == 'plugin') {
			foreach($imported_variables[$key] as $variables) {
				$wpdb->query("UPDATE ".$canvas->variables." SET value = '".addslashes($variables['value'])."' WHERE variable_name = '".addslashes($variables['name'])."' AND parent = '".$old_block->block_id."'");
			}
		}
	}
}

function canvas_import_plugin($filename, $position) {
	global $wpdb, $canvas;
	if(substr($filename, -6) == 'canvas') {
		$plugin = canvas_get_plugin($filename);
		$path = $plugin->functionPath;
		list($plugin_id, $position) = canvas_install_plugin_data($plugin, $position);		
		if (!empty($plugin->variables)) {
			foreach($plugin->variables as $variable) {
				$name = $path.'_'.str_replace(array(' ','.'), '_', addslashes($variable['name']));
				$type = $variable['type'];
				$default = addslashes($variable['default']);
				$description = addslashes($variable['description']);
				$options = $variable['option'];
				canvas_install_variable_data($name, $plugin_id, $type, $default, $description, $options);
			}
		}
	}
	return $plugin;
}

function canvas_import_plugins($position, $dir='') {
	if($dir=='') return false;
	if (substr($dir,-1) != '/') $dir .= '/';
	$files = scandirectory($dir);
	foreach($files as $filename) {
		if(substr($filename, -6) == 'canvas') {
			$plugin = canvas_import_plugin($dir.$filename, $position);
			$position++;
		}
	}
	return array($plugin, $position);
}

function canvas_install_block_data($block_data, $position) {
	global $wpdb, $canvas;
	$name = $block_data['Name'];
	$author = $block_data['Author'];
	$uri = $block_data['URI'];
	$description = $block_data['Description'];
	$group = $block_data['Group'];
	$path = $block_data['Path'];
	$ubi = md5($name.$author.$uri.$description.$group);
	if (!$wpdb->get_var("SELECT block_name FROM ".$canvas->main." WHERE block_name = '$name' AND theme = '".get_option('template')."'") ) {
		$wpdb->query("INSERT INTO ".$canvas->main." (block_name,type,zone,position,author,description,block_group,uri,path,theme,ubi) VALUES ('$name','block','shelf','$position','$author','$description','$group','$uri','$path','".get_option('template')."','$ubi')");    
    	$position++;
    }
    
    return $position;
}

function canvas_install_plugin_data($plugin, $position) {
	global $wpdb, $canvas;
	$name = addslashes($plugin->functionName);
	$author = $plugin->functionAuthor;
	$uri = $plugin->functionUri;
	$description = addslashes($plugin->functionDesc);
	$group = $plugin->functionGroup;
	$path = $plugin->functionPath;
	$ubi = md5($name.$author.$uri.$description.$group.$path);
	if (!$wpdb->get_var("SELECT block_name FROM ".$canvas->main." WHERE block_name = '$name' AND theme = '".get_option('template')."'") ) {
		$wpdb->query("INSERT INTO ".$canvas->main." (block_name,type,zone,position,author,description,block_group,uri,path,theme,ubi) VALUES ('$name','plugin','shelf','$position','$author','$description','$group','$uri','$path','".get_option('template')."','$ubi')");		
    	$position++;
    }
    $plugin_id = mysql_insert_id($wpdb->dbh);

    return array($plugin_id,$position);
}

function canvas_install_variable_data($name, $parent, $type, $default, $description, $options) {
	global $wpdb, $canvas;
	if (!$wpdb->get_var("SELECT variable_name FROM ".$canvas->variables." WHERE variable_name = '$name' AND parent = '$parent'") ) {
		$wpdb->query("INSERT INTO ".$canvas->variables." (variable_name,parent,type,value,default_value,description) VALUES ('$name','$parent','$type','$default','$default','$description')");
		$var_id = $wpdb->get_var("SELECT variable_id FROM ".$canvas->variables." WHERE variable_name = '$name' AND parent = '$parent'");
		
		if (!empty($options)) {
		  foreach($options as $option) {
			$option_name = addslashes($option['name']);
			$option_value = addslashes($option['value']);
			$wpdb->query("INSERT INTO ".$canvas->options." (var_id,option_text,option_value) VALUES ('$var_id','$option_name','$option_value')");
          }
		}
	}
}

function canvas_parse_block_data($filename) {
	$file_data = implode('', file($filename));
	preg_match("|Block Name:(.*)|i", $file_data, $block_name);
	preg_match("|Block URI:(.*)|i", $file_data, $block_uri);
	preg_match("|Description:(.*)|i", $file_data, $description);
	preg_match("|Group:(.*)|i", $file_data, $group);
	preg_match("|Author:(.*)|i", $file_data, $author_name);
	if(preg_match("|Version:(.*)|i", $file_data, $version)) $version = $version[1];
		else $version ='';

	$description = addslashes(trim($description[1]));
	$group = trim($group[1]);

	$name = addslashes(trim($block_name[1]));
	$uri = trim($block_uri[1]);	
	$author = trim($author_name[1]);
	$path = str_replace('\\', '/', $filename);

	return array('Name' => $name, 'Description' => $description, 'Group' => $group, 'Author' => $author, 'URI' => $uri, 'Version' => $version, 'Path' => $path);
}

function canvas_restore_form($xml_path) {
?>
<div class="lbContent">
<h3>Restore from XML
<p>Attempt to restore this theme's layout to the default settings.</p>
<a id="cancel" href="javascript:void(0)" class="lbAction" rel="cancel">Cancel</a>
</h3>
<div>
	<form id="canvas_export">
		<p>Canvas will attempt to restore your current theme's layout and plugin settings to those specified by the author in the original XML file.</p>
		<p>Importing from XML is still experimental, and may result in loss of Canvas-related data.</p>
		<input class="text" type="hidden" id="path_to_xml" name="path_to_xml" value="<?php echo $xml_path; ?>&restore=true" />
		<input type="button" id="import_canvas" name="import_canvas" value="Restore" onclick="Canvas.importXml()"/>
	</form>
	<p id="export_message"></p>
</div>
</div>

<?php
}

if(isset($_GET["canvas_import_form"]) && $_GET["canvas_import_form"] == 'true') canvas_import_form();
if(isset($_GET["canvas_restore_form"]) && $_GET["canvas_restore_form"] == 'true') canvas_restore_form($_GET["xml_path"]);

?>